<template>
  <div ref="boxwrap" class="AlarmTypes-Second">
    <div class="time-pick">
      <span>选择月份 </span>
      <el-date-picker
        v-model="month"
        type="month"
        placeholder="选择月份"
        value-format="yyyy-MM"
        :clearable="false"
        @change="changeMonth"
      />
    </div>
    <div class="main-content" @click="thirdPage">
      <div class="box-wrap">
        <div class="alarmGauge-wrap">
          <!-- 总次数 -->
          <alarm-gauge v-if="Object.keys(responseData).length > 0" id="alarmGauge" height="100%" width="100%" :data="totalCount" />
        </div>
        <div class="level-wrap">
          <div v-for="(value, key) in alLevelPie" :key="'level'+key" :style="{'height': 100 / Object.keys(alLevelPie).length + '%'}">
            <level-pie v-if="showCharts.levelPie" :id="'levelPie'+key" height="100%" width="100%" :data="value" :title="key" />
          </div>
        </div>
        <div class="type-wrap">
          <div v-for="(value, key) in alTypePie" :key="'type'+key" :style="{'height': 100 / Object.keys(alTypePie).length + '%'}">
            <type-pie v-if="showCharts.TypePie" :id="'typePie'+key" height="100%" width="100%" :data="value" :title="key" />
          </div>
        </div>
      </div>
      <div class="box-wrap">
        <div class="topTen-wrap">
          <!-- 前十大占比 -->
          <top-ten-chart v-if="showCharts.topTen" id="topTenChart" height="100%" width="100%" :data="toptenData" />
        </div>
      </div>
      <div class="box-wrap">
        <div class="alarmDay-wrap">
          <!-- 次数日趋势 -->
          <alarm-day-line v-if="showCharts.countDayLine" id="alarmDayLine" height="100%" width="100%" :data="countDayLine" />
        </div>
      </div>
    </div>

    <vxe-modal
      v-model="showThirdPage"
      width="700"
      height="500"
      show-zoom
      class-name="layer-style"
    >
      <template #title>
        <span>报警分类三阶</span>
      </template>
      <template #default>
        <alarm-types-third :params="thirdParam" />
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import AlarmDayLine from './charts/alarm/AlarmDayLine'
import AlarmGauge from './charts/alarm/AlarmGauge-v2'
import TopTenChart from './charts/alarm/TopTenChart'
import LevelPie from './charts/alarm/LevelPie-v2'
import TypePie from './charts/alarm/TypePie-v2'
import { parseTime, cutLineName, sortArrObj } from '@/utils'
import { getSecondOrderCount, getAlertsStatus } from '@/api/screen'
import { getLineByProcess } from '@/api/conf'
import AlarmTypesThird from '@/views/screenThird/AlarmTypesThird.vue'

export default ({
  name: 'AlarmTypesSecond',
  components: { AlarmDayLine, AlarmGauge, TopTenChart, LevelPie, TypePie, AlarmTypesThird },
  filters: {
    cutLineName(str) {
      return str.substring(str.length - 2)
    }
  },
  data() {
    return {
      month: '',
      alarmCount: 50,
      tableHeight: 'auto',
      regionid: '',
      lineId: '',
      lineIds: '',
      query: {
        month: '',
        lineIds: ''
      },
      allLinesObj: {}, // 本制程下所有产线
      alertType: { 0: '安全', 1: '参数', 2: '传感', 3: '电气', 4: '卡板', 5: '开停', 6: '门盖', 7: '系统', 8: '液位' },
      alertLevel: { '一级': [0, 1, 2, 4, 5, 7], '二级': [3, 8], '三级': [6] },
      showCharts: {
        countDayLine: false,
        TypePie: false,
        levelPie: false,
        topTen: false
      },
      responseData: {},
      totalCount: 0, // 左上 报警总次数
      countDayLine: {}, // 左上 报警次数日趋势
      alLevelPie: {}, // 左下 报警等级占比
      alTypePie: {}, // 左下 报警类别占比
      toptenData: {}, // 右上 前十大
      alertTableData: {}, // 右下： 表格
      showThirdPage: false,
      thirdParam: {}
    }
  },
  mounted() {
    this.getDomStyle()
  },
  created() {
    this.month = parseTime(new Date(), '{y}-{m}')
    this.regionid = parseInt(this.$Cookies.get('currentReginid'))
    this.lineId = parseInt(this.$Cookies.get('currentLineId'))
    this.getLineIds()
  },
  methods: {
    getDomStyle() {
      const that = this
      const dom = this.$refs.boxwrap
      this.$erd.listenTo(dom, function(element) {
        that.tableHeight = (dom.clientHeight / 2 - 60) / 2
      })
    },
    getLineIds() {
      // console.log('this.lineId', this.lineId)
      if (this.lineId === 0) {
        getLineByProcess({ regionid: this.regionid }).then(res => {
          this.lineIds = res.data.filter(val => {
            return val.regionid === this.regionid
          }).map(val => {
            return val.id
          }).join(',')
          res.data.forEach(item => {
            this.allLinesObj[item.id] = item
          })
        }).then(() => {
          this.getOrderCount()
          this.alertDetailTable()
        })
      } else {
        this.lineIds = '' + this.lineId
        this.getOrderCount()
        this.alertDetailTable()
      }
    },
    getOrderCount() {
      this.query = {
        month: this.month,
        lineIds: this.lineIds
      }
      // this.resetDatas()
      getSecondOrderCount(this.query).then(res => {
        this.responseData = Object.assign({}, res.data)
        if (this.responseData) {
          this.totalCount = res.data.totalCount
          // 次数日趋势
          let countLineTemp = []
          for (const k in this.responseData.dateGroup) {
            countLineTemp = []
            this.responseData.dateGroup[k].forEach(item => {
              countLineTemp.push([this.month.split('-')[0] + '/' + item.name, item.typeCount])
            })
            this.countDayLine[cutLineName(this.allLinesObj[k].name)] = countLineTemp
          }
          this.showCharts.countDayLine = true

          // 前十大
          const topTenDataObj = {
            xAxis: [],
            datas: {}
          }
          const typeNum = {} // 每个类型的数量
          for (const k in this.alertType) {
            typeNum[this.alertType[k]] = 0
          }
          for (const k in this.responseData.alertSortGroup) {
            const list = this.responseData.alertSortGroup[k]
            let total = 0
            const arr = []
            list.forEach(item => {
              total += item.typeCount
              arr.push({ name: item.name, typeCount: item.typeCount })
              typeNum[item.name] += item.typeCount
            })
            topTenDataObj.datas[k] = {
              lineName: cutLineName(this.allLinesObj[k].name),
              total,
              list: arr
            }
          }

          console.log(topTenDataObj.datas)
          const typeNumArr = [] // 按数量降序后的所有类型，可用于x轴
          for (const k in typeNum) {
            typeNumArr.push({ name: k, typeCount: typeNum[k] })
          }
          typeNumArr.sort(sortArrObj('typeCount', 'desc'))
          // console.log('按数量降序后的全部类型', typeNumArr)
          typeNumArr.forEach(item => {
            topTenDataObj.xAxis.push(item.name)
          })

          // 计算贡献度
          let addCount = 0 // 累计次数
          for (const k in topTenDataObj.datas) {
            topTenDataObj.datas[k].list.forEach(item => {
              addCount += item.typeCount
              item['rate'] = topTenDataObj.datas[k].total === 0 ? 0 : item.typeCount === 0 ? 0 : (addCount / topTenDataObj.datas[k].total * 100).toFixed(1)
            })
          }
          this.toptenData = Object.assign({}, topTenDataObj)
          this.showCharts.topTen = true

          // 等级pie
          const tempLevel = {}
          for (const k in this.responseData.levelGroup) {
            tempLevel[cutLineName(this.allLinesObj[k].name)] = this.responseData.levelGroup[k]
          }
          this.alLevelPie = Object.assign({}, tempLevel)
          this.showCharts.levelPie = true

          // 类别pie
          const tempType = {}
          for (const k in this.responseData.alClassGroup) {
            tempType[cutLineName(this.allLinesObj[k].name)] = this.responseData.alClassGroup[k]
          }
          this.alTypePie = Object.assign({}, tempType)
          this.showCharts.TypePie = true
        } else {
          this.resetDatas()
        }
      })
    },
    resetDatas() {
      this.responseData = {}
      this.totalCount = 0
      this.countDayLine = {}
      this.alLevelPie = {}
      this.alTypePie = {}
      this.toptenData = {}
    },
    changeMonth() {
      this.getOrderCount()
      if (this.showThirdPage) {
        this.thirdParam = {
          month: this.month,
          regionid: this.regionid,
          lineId: this.lineId,
          regionName: '',
          lineName: ''
        }
      }
    },
    // 当前报警明细
    alertDetailTable() {
      getAlertsStatus({ regionid: this.regionid, lineId: this.lineId }).then(res => {
        this.alertTableData = Object.assign({}, res.data)
      })
    },
    thirdPage() {
      this.thirdParam = {
        month: this.month,
        regionid: this.regionid,
        lineId: this.lineId,
        regionName: '',
        lineName: ''
      }
      this.showThirdPage = true
    }
  }
})
</script>

<style lang="scss" scoped>
.el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 120px;
}

.AlarmTypes-Second{
    width: 100%;
    height: 100%;
  .main-content{
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    height: calc(100% - 46px);

    .box-wrap{
      width: 50%;
      height: 50%;

      &:first-child{
        display: flex;

        > div:first-child {
          width: 25%;
          height: 100%;
        }
        > div:not(:first-child) {
          width: calc(75% / 2);
          height: 100%;
        }
      }

      &:nth-child(2n){
        border-left: 1px solid #5967a4;
      }
      &:last-child {
        width: 100%;
        border-top: 1px solid #5967a4;
      }

      .alarmGauge-wrap{
        height: 30%;
        min-height: 50px;
      }
      .alarmDay-wrap{
        height: 100%;
        min-height: 50px;

        #alarmDayLine{
          width: 100%;
          height: 100%;
        }
      }

      .topTen-wrap{
        width: 100%;
        height: 100%;
      }

      // .level-wrap{
      //   height: 40%;
      // }
      // .type-wrap{
      //   width: 100%;
      //   height: 60%;
      // }

      .detail-table {
        width: 100%;
        height: calc(100% - 20px);

        .table-wrap {
          width: 100%;
          height: 50%;
        }
      }

    }

  }

}
</style>
